#!/bin/bash

# 创建输出目录
mkdir -p output

# 使用Python实现
echo "正在设置Python实现..."

# 复制Python文件到输出目录
cp TopMostHost.py output/

# 创建bash包装脚本
cp TopMostHost output/

# 设置执行权限
chmod +x TopMostHost
chmod +x output/TopMostHost
chmod +x output/TopMostHost.py

# 复制到当前目录以便setup功能使用
echo "✅ Python实现设置完成！"
echo "- 可执行文件位于: ./TopMostHost"
echo "- Python脚本位于: ./TopMostHost.py"
echo "- 输出目录: output/"
echo ""
echo "正在更新Native Messaging配置..."

# 尝试更新配置文件
home_dir=$(eval echo ~$USER)
manifest_dir="$home_dir/Library/Application Support/Google/Chrome/NativeMessagingHosts"
manifest_path="$manifest_dir/com.topmost.chrome_window.json"

# 确保目录存在
mkdir -p "$manifest_dir"

# 获取当前脚本路径
current_dir="$( cd "$( dirname "${BASH_SOURCE[0]}" )" && pwd )"
executable_path="$current_dir/TopMostHost"

# 创建manifest内容
cat > "$manifest_path" << EOL
{
  "name": "com.topmost.chrome_window",
  "description": "Chrome窗口置顶原生主机",
  "path": "$executable_path",
  "type": "stdio",
  "allowed_origins": [
    "chrome-extension://fbjlpkbeicpaekkomcahgnhbhoeghijb/"
  ]
}
EOL

echo "✅ 配置更新完成！"
echo "- Native Messaging配置文件: $manifest_path"
echo ""
echo "请重新加载Chrome扩展并测试置顶功能"
echo "- 如需查看日志，请检查: ~/.chrome_window_topmost_log.txt"
echo "- 如需测试主机程序，请运行: ./TopMostHost"


# 设置可执行权限
chmod +x output/TopMostHost
chmod +x output/TopMostHost.py

# 创建manifest文件
echo "Installing to Application Support directory..."
APP_SUPPORT_DIR="$HOME/Library/Application Support/Google/Chrome/NativeMessagingHosts"
mkdir -p "$APP_SUPPORT_DIR"

# 获取当前绝对路径
CURRENT_DIR="$( cd "$( dirname "${BASH_SOURCE[0]}" )" && pwd )"
MANIFEST_CONTENT="{
  \"name\": \"com.topmost.chrome_window\",
  \"description\": \"Chrome窗口置顶原生主机\",
  \"path\": \"$CURRENT_DIR/output/TopMostHost\",
  \"type\": \"stdio\",
  \"allowed_origins\": [
    \"chrome-extension://dkdeinpkanckjmaeknpkidhpaocaceje/\"
  ]
}"

echo "$MANIFEST_CONTENT" > "$APP_SUPPORT_DIR/com.topmost.chrome_window.json"

echo "Build and installation completed successfully!"
echo "Python implementation created at: $CURRENT_DIR/output/TopMostHost"
echo "Manifest installed to: $APP_SUPPORT_DIR/com.topmost.chrome_window.json"
echo "To test the extension, reload it in Chrome and try the window pinning feature."
